//
//  OAuthViewController.swift
//  Microblog
//
//  Created by steaest on 15/7/31.
//  Copyright © 2015年 steaest. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {

    //MARK:搭建界面
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        //设置webView后自带颜色,不需要在viewDidLoad设置颜色
        webView.delegate = self
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    //关闭界面
    func close() {
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //加载授权页面
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
    }
    
    //MARK: webView代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //这句话是什么意思?
        let urlString = request.URL!.absoluteString

        //判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) {
            return true
        }
        
        if let query = request.URL!.query where query.hasPrefix("code=") {
            
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            print("获取授权码"+code)
            
            //换取 Token
            loadAccessToken(code)
        
        }else{
            close()
        }
        return false
    }
    
    private func loadAccessToken(code: String) {
        
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                self.netError()
                return
            }
            
            //字典转模型
            //保存用户数据->模型中加载用户数据
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil {
                    
                    self.netError()
                    return
                }
                //发送通知切换视图控制器 false是什么意思?
                NSNotificationCenter.defaultCenter().postNotificationName(WWRootViewControllerSwitchNotification, object: false)
                
                //关闭控制器 Modal出来的控制器一定注意要dismiss
                self.close()
               
            })
        }
    }
    
    //网络出错处理
    private func netError() {
    
        SVProgressHUD.showInfoWithStatus("网络不给力")
        
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            self.close()
        }
    
    }
    
}
